<!-- src/components/sidebar/FilterSection.vue -->
<template>
  <div class="filter-section">
    <!-- 筛选行 -->
    <el-row class="selection-row" :gutter="10">
      <el-col :span="8">
        <RegionSelector @region-change="handleRegionChange" />
      </el-col>
      <el-col :span="8">
        <el-select v-model="sortOrder" placeholder="排序" class="select-sort" @change="handleSortChange">
          <el-option label="评分" value="rating" />
          <el-option label="搜索量" value="popularity" />
          <el-option label="热度" value="hot" />
          <el-option label="距离" value="distance" />
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-button type="primary" class="gpt-button" @click="openAIRecommendation">
          AI一键生成
        </el-button>
      </el-col>
    </el-row>

    <!-- 搜索行 -->
    <el-row class="search-row" :gutter="10">
    <el-col :span="18">
      <el-input 
        v-model="searchText" 
        placeholder="搜索景点..." 
        clearable 
        @keyup.enter="handleSearch"
        :loading="searching"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </el-col>
    <el-col :span="6">
      <el-button 
        type="primary" 
        @click="handleSearch" 
        :icon="Search"
        :loading="searching"
      >
        搜索
      </el-button>
    </el-col>
  </el-row>

    <!-- AI推荐对话框 -->
    <AIRecommendation ref="aiRecommendationRef" @spots-recommended="handleSpotsRecommended"
    @auto-import-spots="handleAutoImportSpots" 
    />
  </div>
</template>

<script setup>
import { ref , watch} from 'vue'
import { Search } from '@element-plus/icons-vue'
import RegionSelector from './RegionSelector.vue'
import { ElMessage } from 'element-plus'
import AIRecommendation from '../ai/AIInput/AIRecommendation.vue'
import { useLocationStore } from '@/stores/LocationStore' 
import { getCurrentPosition } from '@/utils/location'

const selectedRegion = ref('')
const sortOrder = ref('')
const searchText = ref('')
const searching = ref(false)
const aiRecommendationRef = ref()
const userLocation = ref(null)
const locationStore = useLocationStore() 
const currentRegionId = selectedRegion.value
const filterType = ref('region')
// 合并所有事件
// 合并所有事件
const emit = defineEmits(['filter-change', 'update-spots', 'spots-recommended', 'auto-import-spots'])


// 提交地区变化
const handleRegionChange = (regionId) => {
  console.log('地区选择触发:', regionId)
  selectedRegion.value = regionId
  filterType.value = 'region'  // 更新筛选类型
  
  emit('filter-change', {
    type: sortOrder.value || 'region',
    regionId: regionId,
    query: ''
  })
}

// 提交排序方式变化，如果是按距离排序，需要获取用户位置
const handleSortChange = async () => {
  if (sortOrder.value === 'distance') {
    const location = await getUserLocation()
    if (!location) {
      sortOrder.value = ''
      return
    }
    emit('filter-change', {
      type: 'distance',
      regionId: selectedRegion.value,
      query: '',
      location
    })
  } else {
    emit('filter-change', {
      type: sortOrder.value,
      regionId: selectedRegion.value,
      query: ''
    })
  }
}

const handleAutoImportSpots = (spots) => {
  // 将事件向上传递给SideBar组件
  emit('auto-import-spots', spots)
  
  if (spots.length > 0) {
    ElMessage.success(`已自动导入${spots.length}个推荐景点到您的规划`)
  }
}

// 提交搜索
const handleSearch = () => {
  const query = searchText.value.trim()
  
  if (!query) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  emit('filter-change', {
    type: 'search',
    regionId: null,
    query: query
  })
}

const searchSpot = (spotName) => {
  searchText.value = spotName
  handleSearch()
}
const openAIRecommendation = () => {
  aiRecommendationRef.value.dialogVisible = true
}

const handleSpotsRecommended = (spots) => {
  emit('spots-recommended', spots)
}

// 获取用户位置
const getUserLocation = async () => {
  try {
    const position = locationStore.currentPosition
    if (!position) {
      ElMessage.error('无法获取位置信息')
      return null
    }
    return position
  } catch (error) {
    console.error('获取位置失败:', error)
    ElMessage.error('无法获取位置信息')
    return null
  }
}

watch(selectedRegion, (newRegion) => {
  console.log('地区变化:', newRegion)
})

watch(sortOrder, (newOrder) => {
  console.log('排序方式变化:', newOrder)
})

defineExpose({
  searchSpot
})

</script>

<style scoped>
.filter-section {
  margin-bottom: 20px;
}

.selection-row,
.search-row {
  margin-bottom: 10px;
}

.select-region,
.select-sort,
.gpt-button {
  width: 100%;
  background-color: rgb(2, 127, 134);
}

.search-row .el-button {
  width: 100%;
}

.el-input {
  /* 添加搜索框hover效果 */
  &:hover {
    .el-input__inner {
      border-color: var(--el-color-primary);
    }
  }
}

/* 搜索按钮样式优化 */
.search-button {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>